//
//  PPAlbumPreviewViewController.m
//  pickpic
//
//  Created by Jinxiao on 9/5/16.
//  Copyright © 2016 MicroDream. All rights reserved.
//

#import "PPAlbumPreviewViewController.h"
#import "PPAlbumPictureViewController.h"
#import "PPAssetsPickerViewController.h"
#import "PPAlbumContentViewController.h"

#import "PPAlbumImageFlowActionView.h"

#import "PPAlbumModel.h"


#import "PPAlbumEditContentViewController.h"


@interface PPAlbumPreviewViewController () <PPAssetsPickerViewControllerDelegate,TZImagePickerControllerDelegate>


@end

@implementation PPAlbumPreviewViewController

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)popVc{
    
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)viewDidLoad {
    [super viewDidLoad];


    self.title = _album.title;
    
      self.edgesForExtendedLayout = UIRectEdgeNone;
    
    if (self.title.length > 12 && IS_IPHONE_6){
        self.title = [NSString stringWithFormat:@"%@...",[self.title substringWithRange:NSMakeRange(0, 12)]];
    }

    self.editing = NO;

//    [self setupBackItem];
    
//    self.navigationItem.leftBarButtonItem =[UIBarButtonItem barButtonItemImageIcon:@"nav_back" leftMargin:40 target:self action:@selector(popVc)];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"nav_back"] style:UIBarButtonItemStyleDone target:self action:@selector(popVc)];
    self.navigationItem.leftBarButtonItem.tintColor = BLACK;
    self.view.backgroundColor = WHITE;
    
    
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem barButtonItemWithTitle:@"编辑" target:self action:@selector(editAlbum)];

    
    
    
    if (IS_IOS_8) {
        [self.navigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName:PFFontMedium(16),NSForegroundColorAttributeName:BLACK}];
    }else{
        [self.navigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName:PPFONT(PFBold, 17),NSForegroundColorAttributeName:BLACK}];
    }

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveAlbumDidChangedNotification:) name:PPAlbumManagerDidChangeLocalAlbumsNotification object:nil];

    [self reloadData];
}

- (void)didReceiveAlbumDidChangedNotification:(NSNotification *)notification {
    [self reloadData];
    
    
}

- (void)reloadData {
    
    NSArray <PPAlbumImageModel *> *images = [PPAlbumImageModel where:@{@"auuid" : _album.auuid, @"deleted" : @(NO)}];
    NSArray *sortedImages = nil;
    if(_album.order.integerValue == PPAlbumOrderDesc) {
        sortedImages = images;
    } else {
        sortedImages = [images.reverseObjectEnumerator allObjects];
    }

    NSMutableArray *items = [NSMutableArray array];
    [sortedImages enumerateObjectsUsingBlock:^(PPAlbumImageModel *_Nonnull obj, NSUInteger idx, BOOL *_Nonnull stop) {
        PPAbstractArtwork *artwork = obj.artwork;

        PPImageFlowItem *item = [[PPImageFlowItem alloc] init];
        item.image = artwork.image;
        item.URLString = artwork.URLString;
        item.representedObject = artwork;
        [items addObject:item];
    }];
    self.items = items;

    [self layoutSelections];

    [super reloadData];
}


- (void)editAlbum{

    [MobClick event:@"管理-图册管理-编辑-点击编辑"];
//    PPAlbumContentViewController *contentViewController = [[UIStoryboard storyboardWithName:@"Album" bundle:nil] instantiateViewControllerWithIdentifier:@"PPAlbumContentViewController"];
//    contentViewController.type = PPAlbumContentViewControllerTypeEdit;
//    contentViewController.auuid = self.album.auuid;
//    [self.navigationController pushViewController:contentViewController animated:YES];
    
    
    PPAlbumEditContentViewController *contentViewController = [[PPAlbumEditContentViewController alloc] init];
    contentViewController.type = PPAlbumContentViewControllerTypeEdit;
    contentViewController.auuid = self.album.auuid;    
    [self.navigationController pushViewController:contentViewController animated:YES];
    
    
}
- (void)moreItemDidPressed {
    [MobClick event:@"32"];
    PPAlbumImageFlowActionView *actionView = [[NSBundle mainBundle] loadNibNamed:@"PPAlbumImageFlowActionView" owner:nil options:nil].firstObject;
    actionView.frame = CGRectMake(0, self.navigationController.view.height - actionView.height, self.navigationController.view.width, actionView.height);

    DGPopoverView *popoverView = [[DGPopoverView alloc] initWithContainerView:self.navigationController.view contentView:actionView options:DGPopoverViewAnimationOptionUpward backgroundStyle:DGPopoverViewBackgroundStyleDimmed];

    __weak typeof(self)weakSelf = self;
    __weak typeof(popoverView)weakPopover = popoverView;
    [actionView.cancelButton setActionBlock:^(UIControl *control) {
        [weakPopover dismissAnimated:YES completion:nil];
    } forControlEvents:UIControlEventTouchUpInside];

    [actionView.addButton setActionBlock:^(UIControl *control) {
        [weakPopover dismissAnimated:YES completion:^{
            [MobClick event:@"34"];
//            PPAssetsPickerViewController *assetsViewController = [[PPAssetsPickerViewController alloc] init];
//            assetsViewController.delegate = weakSelf;
//            assetsViewController.userInfo = @{@"type" : @"addImage"};
//            [weakSelf.navigationController pushViewController:assetsViewController animated:YES];
            [weakSelf selectPhoto];
        }];
    } forControlEvents:UIControlEventTouchUpInside];

    [actionView.editButton setActionBlock:^(UIControl *control) {
        [weakPopover dismissAnimated:YES completion:^{
            [MobClick event:@"管理-图册管理-编辑-点击编辑"];
            
            PPAlbumEditContentViewController *contentViewController = [[PPAlbumEditContentViewController alloc] init];
            contentViewController.type = PPAlbumContentViewControllerTypeEdit;
            contentViewController.auuid = self.album.auuid;
            [self.navigationController pushViewController:contentViewController animated:YES];
            
            
//            PPAlbumContentViewController *contentViewController = [[UIStoryboard storyboardWithName:@"Album" bundle:nil] instantiateViewControllerWithIdentifier:@"PPAlbumContentViewController"];
//            contentViewController.type = PPAlbumContentViewControllerTypeEdit;
//            contentViewController.auuid = weakSelf.album.auuid;
//            [weakSelf.navigationController pushViewController:contentViewController animated:YES];
        }];
    } forControlEvents:UIControlEventTouchUpInside];

    [actionView.deleteButton setActionBlock:^(UIControl *control) {
        [weakPopover dismissAnimated:YES completion:^{
            [MobClick event:@"35"];
            [weakSelf enterDeleteMode];
        }];
    } forControlEvents:UIControlEventTouchUpInside];

    [popoverView displayAnimated:YES completion:nil];
}

- (void)enterShareMode {
    self.selectionMode = PPAlbumPreviewViewControllerSelectionModeShare;
    self.editing = YES;
    self.title = @"选择要分享的照片";

    __weak typeof(self)weakSelf = self;
    [self setNavigationLeftTitle:@"取消" titleColor:[UIColor colorWithRGBHex:0xb2b2b2] action:^{
        [weakSelf leaveSelectionMode];
    }];
    [self setNavigationRightTitle:@"确定" titleColor:[UIColor colorWithRGBHex:0xb2b2b2] action:^{

    }];

    [self layoutSelections];
}

- (void)enterDeleteMode {
    self.selectionMode = PPAlbumPreviewViewControllerSelectionModeDelete;
    self.editing = YES;
    self.title = @"选择要删除的照片";

    __weak typeof(self)weakSelf = self;
    [self setNavigationLeftTitle:@"取消" titleColor:[UIColor colorWithRGBHex:0xb2b2b2] action:^{
        [weakSelf leaveSelectionMode];
    }];
    [self setNavigationRightTitle:@"确定" titleColor:[UIColor colorWithRGBHex:0xb2b2b2] action:^{
        [weakSelf deleteItemDidPressed];
    }];

    [self layoutSelections];
}

- (void)leaveSelectionMode {
    self.selectionMode = PPAlbumPreviewViewControllerSelectionModeNone;
    self.editing = NO;
    self.title = self.album.title;

    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon-home-more"] style:UIBarButtonItemStylePlain target:self action:@selector(moreItemDidPressed)];
    self.navigationItem.leftBarButtonItem = [self preferredBackItem];

    [self layoutSelections];
}

- (void)layoutSelections {
    UIBarButtonItem *confirmItem = self.navigationItem.rightBarButtonItem;

    if(_selectionMode == PPAlbumPreviewViewControllerSelectionModeNone) {
        confirmItem.enabled = YES;
//        confirmItem.tintColor = nil;
    } else {
        __block NSInteger selectedCount = 0;
        [self.items enumerateObjectsUsingBlock:^(PPImageFlowItem *_Nonnull obj, NSUInteger idx, BOOL *_Nonnull stop) {
            if(obj.selected) {
                selectedCount++;
            }
        }];

        if(selectedCount == 0) {
            confirmItem.enabled = NO;
//            confirmItem.tintColor = [UIColor colorWithRGBHex:0xb2b2b2];
        } else {
            confirmItem.enabled = YES;
//            confirmItem.tintColor = [UIColor colorWithRGBHex:0xffdd17];
        }
    }
}

- (void)selectedItemsDidChanged {
    [super selectedItemsDidChanged];

    [self layoutSelections];
}

- (void)deleteItemDidPressed {
    __weak typeof(self)weakSelf = self;
    DGBlockAlertView *alertView = [DGBlockAlertView alertWithTitle:@"确认删除图片？" message:nil cancelTitle:@"取消" cancelBlock:nil confirmTitle:@"确定" comfirmBlock:^{

        NSMutableArray *deletedImages = [NSMutableArray array];

        for(PPImageFlowItem *item in weakSelf.items) {
            if(item.selected) {
                PPAbstractArtwork *artwork = item.representedObject;
                [deletedImages addObject:artwork];
            }
        }

        [[PPAlbumManager sharedInstance] offlineModifyAlbumWithAlbumUUID:_album.auuid insertedArtworks:nil modifiedArtworks:nil deletedArtworks:deletedImages tags:nil title:nil description:nil order:nil permission:nil privacy:nil privacyUserIDs:nil coverUUID:nil];

        [weakSelf reloadData];

        [weakSelf leaveSelectionMode];

    }];

    [alertView show];
}


///MARK:点击单张图片预览
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    [MobClick event:@"33"];

    PPAlbumPictureViewController *pictureViewController = [[PPAlbumPictureViewController alloc] init];

    NSMutableArray *artworks = [NSMutableArray array];

    for(PPImageFlowItem *item in self.items) {
        PPAbstractArtwork *artwork = item.representedObject;
        [artworks addObject:artwork];
    }

    pictureViewController.auuid = _album.auuid;
    pictureViewController.artworks = artworks;
    pictureViewController.index = indexPath.row;

    
    [self.navigationController pushViewController:pictureViewController animated:YES];
}
#pragma mark - PPAssetsPickerViewControllerDelegate

- (void)assetsPickerViewControllerDidPressCancel:(PPAssetsPickerViewController *)assetsPickerViewController {
    [self.navigationController popToViewController:self animated:YES];
}
///MARK：进入相册-》确定-》回调
- (void)assetsPickerViewControllerDidPressConfirm:(PPAssetsPickerViewController *)assetsPickerViewController {
    NSMutableArray *insertedArtworks = [NSMutableArray array];

    for(ALAsset *asset in assetsPickerViewController.selectedAssets) {

        PPAbstractArtwork *artwork = [[PPAbstractArtwork alloc] init];
        artwork.uuid = [NSString uuid];
        artwork.image = [asset.image fixOrientation];
        artwork.created = YES;
        [insertedArtworks addObject:artwork];

    }

    [[PPAlbumManager sharedInstance] offlineModifyAlbumWithAlbumUUID:_album.auuid insertedArtworks:insertedArtworks modifiedArtworks:nil deletedArtworks:nil tags:nil title:nil description:nil order:nil permission:nil privacy:nil privacyUserIDs:nil coverUUID:nil];

    [self reloadData];

    [self.navigationController popToViewController:self animated:YES];
}
///MARK:调用相册 - 详情
- (void)selectPhoto{
    
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:50 delegate:self];
    imagePickerVc.naviBgColor = WHITE;
    imagePickerVc.naviTitleColor = BLACK;
    imagePickerVc.naviTitleFont = PPFONT(@"Helvetica-Bold", 17);
    imagePickerVc.barItemTextColor = BLACK;
    imagePickerVc.barItemTextFont = PPFONTSIZE(16);
    imagePickerVc.allowPickingVideo = NO;
    WEAKSELF
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
           NSMutableArray *insertedArtworks = [NSMutableArray array];
        for (UIImage *img in photos) {
            
            PPAbstractArtwork *artwork = [[PPAbstractArtwork alloc] init];
            artwork.uuid = [NSString uuid];
            artwork.image = [img fixOrientation];
            artwork.created = YES;
            [insertedArtworks addObject:artwork];
        }
        
        [[PPAlbumManager sharedInstance] offlineModifyAlbumWithAlbumUUID:_album.auuid insertedArtworks:insertedArtworks modifiedArtworks:nil deletedArtworks:nil tags:nil title:nil description:nil order:nil permission:nil privacy:nil privacyUserIDs:nil coverUUID:nil];
        
        [weakSelf reloadData];
    }];
    
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}
@end
